//
//  SZOAuthViewController.m
//  Weibo
//
//  Created by Zahi on 2017/7/24.
//  Copyright © 2017年 Zahi. All rights reserved.
//

#import "SZOAuthViewController.h"
#import "SZAccountViewModel.h"


@interface SZOAuthViewController ()<UIWebViewDelegate>

/**网页视图**/
@property (nonatomic, strong) UIWebView *webView;

@end

@implementation SZOAuthViewController


#pragma mark - 视图加载完成
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupView];
}

#pragma mark - 加载视图
- (void)loadView
{

    _webView = [UIWebView new];
    self.view = _webView;
}

#pragma mark - 设置视图
- (void)setupView
{
    
    // 设置导航栏
    [self setupNav];


    // 加载网页数据
    [self loadWebData];
    
    self.webView.delegate = self;
    
}

#pragma mark - 加载网页数据
- (void)loadWebData
{
    
    NSString *URLString = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",AppKey,Redirect_uri];
    NSURL *url = [NSURL URLWithString:URLString];
    
    [_webView loadRequest:[NSURLRequest requestWithURL:url]];
}


#pragma mark - <UIWebViewDelegate>
#pragma mark 是否通过请求开始加载
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{

    // 是否含有前缀 回调页
    BOOL isRedirect_uri = [request.URL.absoluteString hasPrefix:Redirect_uri];
    if (isRedirect_uri) { // 是
        // 获取链接后面的参数
        NSString *query = request.URL.query;
        
        if ([query hasPrefix:@"code="]) {
        
            NSString *code = [query substringFromIndex:[@"code=" length]];
            
            [SZAccountViewModel.shared obtainAccessTokenWithCode:code callBack:^(BOOL isOK) {
                if (isOK) {
                    NSLog(@"登录成功");
                    
                    // 需要控制器先销毁 在切换控制器 否则mainVC没能释放
                    [self dismissViewControllerAnimated:YES completion:^{
                       
                        [kNotificationCenter postNotificationName:SwitchRootVCNotificationName object:self];
                    }];
                     
                } else {
                    NSLog(@"登录失败");
                }
            }];
            
         
        } else { // 取消授权
            
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        // 不加载页面
        return NO;
    }
    
    return YES;
}

#pragma mark 已经开始加载
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [SVProgressHUD show];
}

#pragma mark 已经加载完成
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [SVProgressHUD dismiss];
}

#pragma mark 加载失败
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [SVProgressHUD dismiss];
}

#pragma mark - 设置导航栏
- (void)setupNav
{
    self.navigationItem.title = @"微博登录";
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithTitle:@"取消" image:nil target:self action:@selector(cancalButtonClick)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithTitle:@"自动填充" image:nil target:self action:@selector(autoFillButtonClick)];
}

#pragma mark - 监听按钮的点击

- (void)autoFillButtonClick
{
    [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('userId').value = '18627948881';document.getElementById('passwd').value = 'H';document.getElementById('passwd').focus();"];
}

- (void)cancalButtonClick
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
